package com.haixiaoke.saas.house.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.TreeUtil.TreeUtil;
import com.haixiaoke.saas.house.domain.*;
import com.haixiaoke.saas.house.mapper.EstateMapper;
import com.haixiaoke.saas.house.service.IBuildingService;
import com.haixiaoke.saas.house.service.IEstateService;
import com.haixiaoke.saas.common.Node;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.house.service.IUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 楼盘信息Service业务层处理
 *
 * @author xiaolong
 * @date 2023-10-16
 */
@Service
public class EstateServiceImpl implements IEstateService {
    @Autowired
    private EstateMapper estateMapper;
    @Autowired
    private IBuildingService iBuildingService;
    @Autowired
    private IHouseService iHouseService;
    @Autowired
    private IUnitService iUnitService;

    /**
     * 查询楼盘信息
     *
     * @param estateId 楼盘信息主键
     * @return 楼盘信息
     */
    @Override
    public Estate selectEstateByEstateId(String estateId) {
        Estate estate = estateMapper.selectEstateByEstateId(estateId);
        // 查询楼栋数量
        Integer buildingNumber = iBuildingService.selectBuildingByBuildingNumber(estateId, Building.DEL_FLAG_YES, TenantContext.getTenantId());
        // 查询单位数量
        Integer unitNumber = 0;
        List<Building> buildingList = iBuildingService.selectBuildingByEstateId(estateId, Building.DEL_FLAG_YES);
        if (CollectionUtil.isNotEmpty(buildingList)) {
            for (Building building : buildingList) {
                unitNumber += iUnitService.selectUnitByUnitNumber(building.getBuildingId(), Unit.DEL_FLAG_YES, TenantContext.getTenantId());
            }
        }
        // 查询房间数量
        Integer houseNumber = iHouseService.selectHouseByHouseNumber(estateId, null, TenantContext.getTenantId());
        estate.setBuildingNumber(buildingNumber);
        estate.setUnitNumber(unitNumber);
        estate.setHouseNumber(houseNumber);
        return estate;
    }

    /**
     * 查询楼盘信息列表
     *
     * @param estate 楼盘信息
     * @return 楼盘信息
     */
    @Override
    public List<Estate> selectEstateList(Estate estate) {
        return estateMapper.selectEstateList(estate);
    }

    /**
     * 新增楼盘信息
     *
     * @param estate 楼盘信息
     * @param userId
     * @return 结果
     */
    @Override
    @Transactional
    public int insertEstate(Estate estate, Long userId) {
        if (estate.getEstateName().length() > 10) {
            throw new ServiceException("楼盘名称不能超过10个字");
        }
        if (estate.getPremisesAddress().length() > 30) {
            throw new ServiceException("小区地址不能超过30个字");
        }

        Estate sqlEstate = estateMapper.selectEstateByEstateName(estate.getEstateName(),TenantContext.getTenantId());
        if (ObjectUtil.isNotEmpty(sqlEstate)) {
            throw new ServiceException("该楼盘名称已存在");
        }
        estate.setCreateTime(DateUtils.getNowDate());
        estate.setOperatorId(userId);
        return estateMapper.insertEstate(estate);
    }

    /**
     * 修改楼盘信息
     *
     * @param estate 楼盘信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateEstate(Estate estate) {
        Estate byEstateId = estateMapper.selectEstateByEstateId(estate.getEstateId());
        if (!TenantContext.getTenantId().equals(byEstateId.getTenantId())) {
            return 0;
        }
        Estate sqlEstate = estateMapper.selectEstateByEstateName(estate.getEstateName(),TenantContext.getTenantId());
        if (ObjectUtil.isNotEmpty(sqlEstate)) {
            if (!sqlEstate.getEstateId().equals(estate.getEstateId())) {
                throw new ServiceException("该楼盘名称已存在");
            }
        }
        List<Building> buildingList = iBuildingService.selectBuildingByEstateId(estate.getEstateId(), Estate.DEL_FLAG_YES);
        if (CollectionUtil.isNotEmpty(buildingList)) {
            for (Building building : buildingList) {
                building.setEstateType(estate.getEstateType());
                building.setEstateName(estate.getEstateName());
                building.setPropertyId(estate.getPropertyId());
                building.setProvinceId(estate.getProvinceId());
                building.setCityId(estate.getCityId());
                building.setDistrictId(estate.getDistrictId());
                building.setStreetId(estate.getStreetId());
                building.setCommunityId(estate.getCommunityId());
                building.setPremisesAddress(estate.getPremisesAddress());
                building.setPropertyName(estate.getPropertyName());
                building.setCityName(estate.getCityName());
                building.setDistrictName(estate.getDistrictName());
                building.setStreetName(estate.getStreetName());
                building.setCommunityName(estate.getCommunityName());
                iBuildingService.updateBuilding(building);
            }
        }
        estate.setUpdateTime(DateUtils.getNowDate());
        return estateMapper.updateEstate(estate);
    }

    /**
     * 批量删除楼盘信息
     *
     * @param estateIds 需要删除的楼盘信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteEstateByEstateIds(String[] estateIds) {
        Estate newEstate = new Estate();
        newEstate.setTenantId(TenantContext.getTenantId());
        newEstate.setEstateIds(estateIds);
        List<Estate> estateList = estateMapper.selectEstateByEstateIds(newEstate);
        if (estateList.size() < estateIds.length) {
            return 0;
        }

        for (String estateId : estateIds) {
            Estate estate = estateMapper.selectEstateByEstateId(estateId);
            Building building = new Building();
            building.setEstateId(estateId);
            List<Building> buildingList = iBuildingService.selectBuildingList(building);
            if (CollectionUtil.isNotEmpty(buildingList)) {
                throw new ServiceException(estate.getEstateName() + "楼盘，存在楼栋不可删除！");
            }
            estate.setUpdateTime(DateUtils.getNowDate());
            estate.setDelFlag(Estate.DEL_FLAG_NO);
            estateMapper.updateEstate(estate);
        }

        return 1;
    }

    /**
     * 删除楼盘信息信息
     *
     * @param estateId 楼盘信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteEstateByEstateId(String estateId) {
        return estateMapper.deleteEstateByEstateId(estateId);
    }

    /**
     * 统计楼盘数据
     *
     * @return
     */
    @Override
    public Estate getStatistics() {
        Estate estate = new Estate();
        // 查询楼盘数量
        Integer estateNumber = estateMapper.selectEstateByEstateNumber(TenantContext.getTenantId());
        // 查询楼栋数量
        Integer buildingNumber = iBuildingService.selectBuildingByBuildingNumber(null, Building.DEL_FLAG_YES, TenantContext.getTenantId());
        // 查询房间数量
        Integer houseNumber = iHouseService.selectHouseByHouseNumber(null, null, TenantContext.getTenantId());
        estate.setEstateNumber(estateNumber);
        estate.setBuildingNumber(buildingNumber);
        estate.setHouseNumber(houseNumber);
        return estate;
    }

    @Override
    public List<EstateTree> selectEstateTreeList(House house) {
        List<EstateTree> estateTrees = estateMapper.selectEstateTreeList(house);
        return TreeUtil.generateTree(estateTrees);
    }

    @Override
    public List<Node> selectEstateLevelList(Estate estate) {
        return estateMapper.selectEstateLevelList(estate);
    }

    @Override
    public List<Estate> selectEstateListInfo(Estate estate) {
        List<Estate> estateList = estateMapper.selectEstateList(estate);
        if (CollectionUtil.isNotEmpty(estateList)) {
            for (Estate estate1 : estateList) {
                // 查询楼栋数量
                Integer buildingNumber = iBuildingService.selectBuildingByBuildingNumber(estate1.getEstateId(), Building.DEL_FLAG_YES, TenantContext.getTenantId());
                // 查询单位数量
                Integer unitNumber = 0;
                List<Building> buildingList = iBuildingService.selectBuildingByEstateId(estate1.getEstateId(), Building.DEL_FLAG_YES);
                if (CollectionUtil.isNotEmpty(buildingList)) {
                    for (Building building : buildingList) {
                        unitNumber += iUnitService.selectUnitByUnitNumber(building.getBuildingId(), Unit.DEL_FLAG_YES, TenantContext.getTenantId());
                    }
                }
                // 查询房间数量
                Integer houseNumber = iHouseService.selectHouseByHouseNumber(estate1.getEstateId(), null, TenantContext.getTenantId());
                estate1.setBuildingNumber(buildingNumber);
                estate1.setUnitNumber(unitNumber);
                estate1.setHouseNumber(houseNumber);
            }
        }
        return estateList;
    }

    @Override
    public Estate selectEstateByEstateIdInfo(String estateId) {
        return estateMapper.selectEstateByEstateId(estateId);
    }

    @Override
    public Estate selectEstateByEstateName(String estateName, String tenantId) {
        return estateMapper.selectEstateByEstateName(estateName, tenantId);
    }


}
